/**
 * Copyright (C) 2014 Domon.Xie All Rights Reserved.
 *
 * ModelScannerConfigurer.java
 * 2014年10月19日 下午6:58:18
 */
package org.domon.mybatis.model;

import static org.springframework.util.Assert.notNull;

import org.domon.mybatis.bind.ModelRegistry;
import org.domon.mybatis.sql.DbNameGenerator;
import org.domon.mybatis.sql.support.DefaultDbNameGenerator;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.StringUtils;

/**
 * @author Domon.Xie
 * 
 */
public class ModelScannerConfigurer implements BeanDefinitionRegistryPostProcessor, InitializingBean, ApplicationContextAware {

    /**
     * 数据模型包路径
     */
    protected String modelPackage;
    
    protected ModelRegistry modelRegistry;

    private ApplicationContext applicationContext;
    
    private DbNameGenerator dbNameGenerator = new DefaultDbNameGenerator();
    
    public void setDbNameGenerator(DbNameGenerator dbNameGenerator) {
        this.dbNameGenerator = dbNameGenerator == null ? new DefaultDbNameGenerator() : dbNameGenerator;
    }

    public void setModelPackage(String modelPackage) {
        this.modelPackage = modelPackage;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        notNull(this.modelPackage, "MybatisHepler: Model包路径不可为空");
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        ClassPathModelScanner scanner = new ClassPathModelScanner(registry);

        scanner.setResourceLoader(this.applicationContext);
        scanner.setDbNameGenerator(dbNameGenerator);
        scanner.registerFilters();
        scanner.scan(StringUtils.tokenizeToStringArray(this.modelPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        // do nothing
    }
}
